﻿using System;
using System.Linq;
using ReagentStore.DAL;
using ReagentStore.ERM;
using ReagentStore.Resources.Properties;
using ReagentStore.UTL;

namespace ReagentStore.BLL
{
	public class CatalogBLL
	{
		public readonly CatalogDAL DALAccessor = new CatalogDAL();

		private void CheckParams(Catalog catalog)
		{
			catalog.Name = catalog.Name.Regular();

			if (string.IsNullOrEmpty(catalog.Name))
				throw new ApplicationException(DefaultResources.CATALOG_INVALID_PARAM);

			Catalog exist =
				DALAccessor.GetEntities().SingleOrDefault(
					s => catalog.Name.Equals(s.Name, StringComparison.CurrentCultureIgnoreCase));
			if (exist != null)
				throw new ApplicationException(DefaultResources.CATALOG_EXIST);
		}

		private void CheckEntityUpdatable(Catalog catalog)
		{
			Catalog updation = DALAccessor.GetEntityById(catalog.CatalogID);
			if (updation == null)
				throw new ApplicationException(DefaultResources.CATALOG_NOT_FOUND);
			if (updation.Name.Equals(DefaultResources.DEFAULT_CATALOG_NAME, StringComparison.CurrentCultureIgnoreCase))
				throw new ApplicationException(DefaultResources.CATALOG_UPDATE_NONPERMIT);
		}

		public void Insert(Catalog catalog)
		{
			CheckParams(catalog);
			catalog.CatalogID = 0;
			DALAccessor.Insert(catalog);
		}

		public void Update(Catalog catalog)
		{
			CheckParams(catalog);
			CheckEntityUpdatable(catalog);
			DALAccessor.Update(catalog);
		}

		public void Delete(Catalog catalog)
		{
			CheckEntityUpdatable(catalog);
			DALAccessor.Delete(catalog);
		}
	}
}